package com.zs.test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author ZhouShuang
 * @version 17
 * @Title
 * @date 2025/6/7 上午10:37
 */
public class AccessPersonConstructors2 {
    public static void main(String [] args){
        try{
            Class<?> clz = Class.forName("com.zs.pojo.Person");

            //获取Person的无参构造方法
            Constructor<?> constructor = clz.getConstructor();
            //Person的无参构造方法为public，这里可以直接访问
            Object object = constructor.newInstance();
            System.out.println(object);

            //获取Person的单个参数的构造方法
            Constructor<?> constructor1 = clz.getDeclaredConstructor(String.class);
            //Person的单个参数构造方法为private，这里已超出其访问范围，不能直接访问
            //通过setAccessible方法，设定为可以访问
            constructor1.setAccessible(true);
            Object object1 = constructor1.newInstance("New Person");
            System.out.println(object1);

            //获取Person的三参构造
            Constructor<?> constructor2  = clz.getDeclaredConstructor(String.class,String.class,String.class);
            //Person的三参构造为protected，这里已经超出其访问范围，不能直接访问
            //通过setAccessible方法，设定为可以访问
            constructor2.setAccessible(true);
            Object object2 = constructor2.newInstance("New Person","beijing","Hello!");
            System.out.println(object2);
        } catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException | InstantiationException |
                 IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
